package com.lyc.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.lyc.dao.CountryInfoDAO;
import com.lyc.dao.imp.CountryInfoDAOImpl;
import com.lyc.entity.CountryInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/country-add.let")
public class CountryAddServlet extends HttpServlet {

	private CountryInfoDAO dao = new CountryInfoDAOImpl();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.reset();

		response.setContentType("application/json;charset=UTF-8");
		try {
			// 将前端传递过来的表单数据设置到实体对象中
			// 注意：如果实体属性是非String的，则需要进行转换
			// 注意：该步骤适当加入校验
			CountryInfo e = new CountryInfo();
			String code = request.getParameter("countryCode");
			if (code == null || "".equals(code)) {
				throw new ServletException("国家编码不能为空");
			}
			if (!code.matches("^\\w+$")) {
				throw new ServletException("国家编码只能是字母");
			}
			e.setCountryCode(request.getParameter("countryCode"));
			e.setCountryUri(request.getParameter("countryUri"));
			e.setCountryNameCn(request.getParameter("countryNameCn"));
			e.setCountryNameEn(request.getParameter("countryNameEn"));
			e.setCountryName(request.getParameter("countryName"));

			try {
				dao.insert(e);
				response.getWriter().print("{\"ok\":true}");
			} catch (Exception ex) {
				throw new ServletException("国家代码不能重复", ex);
			}
		} catch (Exception e) {
			response.getWriter().print("{\"ok\":false,\"msg\":\"" + e.getMessage() + "\"}");
		}

		response.flushBuffer();
	}
}
